<template>
  <el-row :gutter="20">
    <!-- 左侧章节目录 -->
    <el-col :span="4">
      <el-menu :default-active="String(selectedChapter)" @select="handleChapterSelect">
        <el-menu-item v-for="chapter in chapters" :key="chapter.id" :index="String(chapter.id)">
          {{ chapter.title }}
        </el-menu-item>
      </el-menu>
    </el-col>
    <!-- 右侧知识点列表 -->
    <el-col :span="20">
      <el-card v-for="knowledge in knowledgeList" :key="knowledge.id" class="mb-20">
        <h3>{{ knowledge.title }}</h3>
        <div v-html="formatContent(knowledge.content)"></div>
        <div v-if="knowledge.exampleCode">
          <h4>示例代码：</h4>
          <pre><code>{{ knowledge.exampleCode }}</code></pre>
        </div>
      </el-card>
    </el-col>
  </el-row>
</template>

<script>
export default {
  data() {
    return {
      chapters: [],
      selectedChapter: null,
      knowledgeList: []
    }
  },
  methods: {
    loadChapters() {
      this.$http.get(this.$http.adornUrl('/learn/basic/chapters'))
        .then(({ data }) => {
          if (data.code === 0) {
            this.chapters = data.data
            if (this.chapters.length > 0) {
              this.selectedChapter = this.chapters[0].id
              this.loadKnowledge(this.selectedChapter)
            }
          }
        })
    },
    loadKnowledge(chapterId) {
      this.$http.get(this.$http.adornUrl('/learn/basic/knowledge'), { params: { chapterId } })
        .then(({ data }) => {
          if (data.code === 0) {
            this.knowledgeList = data.data
          }
        })
    },
    handleChapterSelect(chapterId) {
      this.selectedChapter = parseInt(chapterId)
      this.loadKnowledge(this.selectedChapter)
    },
    formatContent(content) {
      return content ? content.replace(/\n/g, '<br>') : ''
    }
  },
  mounted() {
    this.loadChapters()
  }
}
</script>

<style scoped>
.mb-20 { margin-bottom: 20px; }
</style>
